<?php
/**
 * Created by PhpStorm.
 * User: Steven
 * Date: 2017/6/19
 * Time: 9:30
 */

namespace app\jiaxiaotong\model;


use app\classes\model\ClassModel;
use think\Log;
use think\Model;

class CourseScheduleModel extends Model
{
    public function __construct($data = [])
    {
        parent::__construct($data);
    }

    /**
     * 获取排课列表
     * @param array $filter
     * @param array $order
     * @param int $limit
     * @param $query
     * @return \think\Paginator
     */
    public function getSchedule($filter=[], $order=[], $limit=10, $query)
    {
        //默认条件
        $where = [];
        if(!empty($filter) && is_array($filter)){
            $where = array_merge($where,$filter);
        }

        //默认排序
        $sort = ['id'=>'asc'];
        if(!empty($order) && is_array($order)){
            $sort = array_merge($order,$sort);
        }

        //分页url额外参数
        $page_query['query'] = [];
        if(!empty($query) && is_array($query)){
            $page_query['query'] = $query;
        }

        $data = $this->alias('crs')
            ->field('crs.*,sc.name as school_name,cl.name as class_name,clr.name as classroom_name,cr.course_hour,cr.course_name,u.user_login as user_name')
            ->join('class cl','crs.class_id=cl.id')
            ->join('classroom clr','crs.classroom_id=clr.id')
            ->join('school sc','cl.school_id=sc.id')
            ->join('course cr','cl.course_id=cr.id')
            ->join('user u', 'crs.teacher_id=u.id')
            ->where($where)
            ->order($sort)
            ->paginate($limit,false,$page_query);

        return $data;
    }

    /**
     * 添加排课
     * @param array $data
     * @return bool
     */
    public function addSchedule($data=[])
    {
        $result = true;
        if(empty($data)){
            $result = false;
        }else{
            self::startTrans();
            try{
                $this->allowField(true)->insertAll($data);

                self::commit();
            }catch(\Exception $e){
                self::rollback();
                $result = false;
            }
        }

        return $result;
    }

    /**
     * @param $id
     * @param $cur_time
     * @return bool
     */
    public function deleteSchedule($id, $cur_time)
    {
        $result = true;
        if(empty($id)){
            $result = false;
        }else{
            if(empty($cur_time)){
                //当前时间
                $cur_time = time();
            }
            if(is_array($id)){
                //批量删除
                self::startTrans();
                try{
                    $this->where(['id' => ['in', $id]])->delete();

                    self::commit();
                }catch(\Exception $e){
                    self::rollback();
                    $result = false;
                }
            }else{
                //单一删除
                self::startTrans();
                try{
                    $this->where(['id' => $id])->delete();

                    self::commit();
                }catch(\Exception $e){
                    self::rollback();
                    $result = false;
                }
            }
        }

        return $result;
    }

    /**
     * 重新排课(从指定日期开始排课)
     * @param int $date_timestamp
     * @param int $shop_id
     * @return bool
     */
    public function reSchedules($date_timestamp=0, $shop_id=1)
    {
        $result = true;
        $class_ids = [];//班级ID
        $adjust_mdl = new CourseAdjustModel();//调课模型
        $class_mdl = new ClassModel();//班级模型

        if(empty($date_timestamp)){
            return false;
        }

        //获取当日之后的所有排课情况
        $schedules = $this->alias('cs')
            ->field('cs.id,cs.class_id')
            ->join('class cl', 'cs.class_id=cl.id')
            ->where('cl.shop_id', '=', $shop_id)
            ->where('cs.schedule', '<>', 0)//非临时加课
            ->where('cs.date', '>= time', $date_timestamp)
            ->group('cs.class_id')//以班级分组
            ->select();

        if(count($schedules) > 0){
            $schedules = $schedules->toArray();
            $class_ids = array_column($schedules,'class_id');
        }
        if(count($class_ids) > 0 ) {
            self::startTrans();
            try{
                foreach ($class_ids as $val) {
                    //获取开始的进度
                    $schedule_single = $this->where('class_id', '=', $val)
                        ->where('schedule', '<>', 0)//非临时加课
                        ->where('date', '>= time', $date_timestamp)
                        ->order('schedule','asc')
                        ->find();
                    if(count($schedule_single) > 0){
                        //开始进度值
                        $schedule_num = $schedule_single['schedule'];
                    }else{
                        $schedule_num = 0;
                    }

                    //获取调课时间
                    $adjust_data = $adjust_mdl->where('class_id', '=', $val)->find();
                    if (count($adjust_data) > 0) {
                        //调课时间
                        $adjust_date[0] = $adjust_data['start_date'];
                        $adjust_date[1] = $adjust_data['end_date'];
                    } else {
                        $adjust_date = [];
                    }

                    //从当日后重新排课
                    $course_schedules = $class_mdl->getCourseTime($val, $date_timestamp, 0, $shop_id, $adjust_date, $schedule_num);
                    if (count($course_schedules) > 0) {
                        //先删除原有的排课
                        $this->where('class_id', '=', $val)
                            ->where('schedule', '<>', 0)//非临时加课
                            ->where('date', '>= time', $date_timestamp)
                            ->delete();

                        //保存新排课
                        $new_data = [];
                        foreach ($course_schedules as $k => $v) {
                            $new_data[$k] = [
                                'class_id' => $v['class_id'],
                                'classroom_id' => $v['classroom_id'],
                                'teacher_id' => $v['teacher_id'],
                                'date' => strtotime($v['date']),
                                'start_time' => $v['start_time'],
                                'end_time' => $v['end_time'],
                                'week' => $v['cur_week'],
                                'schedule' => $v['schedule'],
                            ];
                        }
                        $result = $this->addSchedule($new_data);
                        if (!$result) {
                            $result = false;
                        }
                    }
                }

                self::commit();
            }catch(\Exception $e){
                self::rollback();
                $result = false;
            }
        }
        return $result;
    }

}